package cn.wolfcode.web.controller;

import cn.wolfcode.common.constants.CommonConstants;
import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.CommonCodeMsg;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.DateUtil;
import cn.wolfcode.util.UserUtil;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lanxw
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderInfoController {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private IOrderInfoService orderInfoService;

    /**
     * 秒杀接口
     * @param time
     * @param seckillId
     * @param request
     * @return
     */
    @RequestMapping("/doSeckill")
    public Result<String> doSeckill(Integer time , Long seckillId, HttpServletRequest request){
        SeckillProductVo seckillProductVo = seckillProductService.find(time,seckillId);
        boolean legalTime = DateUtil.isLegalTime(seckillProductVo.getStartDate(),seckillProductVo.getTime());
        if(!legalTime){
            return Result.error(CommonCodeMsg.ILLEGAL_OPERATION);
        }
        // 每个用户只能抢购一个商品
        String orderKey = SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(String.valueOf(seckillId));
        String token = request.getHeader(CommonConstants.TOKEN_NAME);
        String phone = UserUtil.getUserPhone(redisTemplate,token);
        if(redisTemplate.opsForSet().isMember(orderKey,phone)){
            return Result.error(SeckillCodeMsg.REPEAT_SECKILL);
        }
        // 通过redis实现，redis的扣减和读取是原子性的
        String seckillStockCountKey = SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(String.valueOf(time));
        Long remain = redisTemplate.opsForHash().increment(seckillStockCountKey,String.valueOf(seckillId),-1);
        // 库存数量足够
        if(remain < 0){
            return Result.error(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        // 全部符合要求，开始下单 -> 创建订单，扣减库存  -》 改成使用mq异步下单
//        OrderInfo orderInfo = orderInfoService.doSeckill(phone, seckillProductVo);
        OrderMessage message = new OrderMessage(time,seckillId,token,Long.valueOf(phone));
        rocketMQTemplate.syncSend(MQConstant.ORDER_PEDDING_TOPIC,message);
        return Result.success();
    }

    @RequestMapping("/find")
    @RequireLogin
    public Result<OrderInfo> find(HttpServletRequest request,String orderNo){
        OrderInfo orderInfo = orderInfoService.findByOrderNo(orderNo);
        String token = request.getHeader(CommonConstants.TOKEN_NAME);
        String phone = UserUtil.getUserPhone(redisTemplate,token);
        if(!phone.equals(String.valueOf(orderInfo.getUserId()))){
            return Result.error(CommonCodeMsg.ILLEGAL_OPERATION);
        }
        return Result.success(orderInfo);
    }

}
